package com.hotdog.servlet;

import com.hotdog.mapper.UserMapper;
import com.hotdog.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@WebServlet(name = "AddServlet", value = "/AddServlet")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String u = request.getParameter("username");
        String password = request.getParameter("password");
        String username = new String(u.getBytes(StandardCharsets.ISO_8859_1), "UTF-8");

        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        System.out.println(username+password);
         User users = mapper.selectAll(username,password);

        if(users==null){
            int add = mapper.add(username,password);
            sqlSession.commit();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("添加成功");
        }else {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("添加失败,用户已存在");
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                 doGet(request,response);
    }
}
